package com.reworkssm.mybatisdemo.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Maps;
import com.reworkssm.mybatisdemo.domain.*;
import com.reworkssm.mybatisdemo.domain.vo.OrderVo;
import com.reworkssm.mybatisdemo.service.OrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

@Controller
@RequestMapping("/order/")
@SessionAttributes({"order"})
public class OrderController {
/*    private static final long serialVersionUID = -6171288227470176272L;
    private static final String CONFIRM_ORDER = "order/ConfirmOrder.jsp";
    private static final String LIST_ORDERS = "/order/ListOrders.jsp";
    private static final String NEW_ORDER = "/order/NewOrderForm.jsp";
    private static final String SHIPPING = "/order/ShippingForm.jsp";
    private static final String VIEW_ORDER = "/order/ViewOrder.jsp";*/



    private Logger logger = LoggerFactory.getLogger(OrderController.class);

    @Autowired
    private OrderService OrderService;

    //20200607修改 OrderManageController
    @RequestMapping("list.do")
    @ResponseBody
    public ServerResponse<PageInfo> list(HttpSession session, @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                         @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        User currentUser = (User) session.getAttribute(Const.CURRENT_USER);
        if (currentUser == null) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(), ResponseCode.NEED_LOGIN.getDesc());
        }
        if (currentUser.getRole() == Const.Role.ROLE_ADMIN) {
            //获取后台订单列表的分页信息
            return OrderService.manageList(pageNum, pageSize);
        }
        return ServerResponse.createByErrorMessage("用户无权限");
    }

    @RequestMapping("detail.do")
    @ResponseBody
    public ServerResponse<OrderVo> detail(HttpSession session, Long orderNo) {
        User currentUser = (User) session.getAttribute(Const.CURRENT_USER);
        if (currentUser == null) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(), ResponseCode.NEED_LOGIN.getDesc());
        }
        if (currentUser.getRole() == Const.Role.ROLE_ADMIN) {
            //获取后台订单明细的分页信息
            return OrderService.manageDetail(orderNo);
        }
        return ServerResponse.createByErrorMessage("用户无权限");
    }

    @RequestMapping("search.do")
    @ResponseBody
    public ServerResponse<PageInfo> search(HttpSession session, Long orderNo, @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                           @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        User currentUser = (User) session.getAttribute(Const.CURRENT_USER);
        if (currentUser == null) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(), ResponseCode.NEED_LOGIN.getDesc());
        }
        if (currentUser.getRole() == Const.Role.ROLE_ADMIN) {
            //获取后台搜索订单
            return OrderService.manageSearch(orderNo, pageNum, pageSize);
        }
        return ServerResponse.createByErrorMessage("用户无权限");
    }

    @RequestMapping("send_goods.do")
    @ResponseBody
    public ServerResponse<String> sendGoods(HttpSession session, Long orderNo) {
        User currentUser = (User) session.getAttribute(Const.CURRENT_USER);
        if (currentUser == null) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(), ResponseCode.NEED_LOGIN.getDesc());
        }
        if (currentUser.getRole() == Const.Role.ROLE_ADMIN) {
            //发货
            return OrderService.manageSendGoods(orderNo);
        }
        return ServerResponse.createByErrorMessage("用户无权限");
    }



    @RequestMapping("create.do")
    @ResponseBody
    public ServerResponse create(HttpSession session, Integer shippingId) {
        User currentUser = (User) session.getAttribute(Const.CURRENT_USER);
        if (currentUser == null) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(), ResponseCode.NEED_LOGIN.getDesc());
        }

        return OrderService.createOrder(currentUser.getId(), shippingId);
    }


    @RequestMapping("cancel.do")
    @ResponseBody
    public ServerResponse cancel(HttpSession session, Long orderNo) {
        User currentUser = (User) session.getAttribute(Const.CURRENT_USER);
        if (currentUser == null) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(), ResponseCode.NEED_LOGIN.getDesc());
        }
        return OrderService.cancel(currentUser.getId(), orderNo);
    }

    @RequestMapping("get_order_cart_product.do")
    @ResponseBody
    public ServerResponse getOrderCartProduct(HttpSession session) {
        User currentUser = (User) session.getAttribute(Const.CURRENT_USER);
        if (currentUser == null) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(), ResponseCode.NEED_LOGIN.getDesc());
        }
        return OrderService.getOrderCartProduct(currentUser.getId());
    }



    @RequestMapping("pay.do")
    @ResponseBody
    public ServerResponse pay(HttpSession session, Long orderNo, HttpServletRequest request) {
        User currentUser = (User) session.getAttribute(Const.CURRENT_USER);
        if (currentUser == null) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(), ResponseCode.NEED_LOGIN.getDesc());
        }
        String path = request.getSession().getServletContext().getRealPath("upload");
        return OrderService.pay(currentUser.getId(), path, orderNo);
    }

    @RequestMapping("alipay_callback.do")
    @ResponseBody
    public Object alipayCallback(HttpServletRequest request) {
        Map<String, String> params = Maps.newHashMap();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }
        logger.info("支付宝回调，sign:{},trade_status:{},参数:{}", params.get("sign"), params.get("trade_status"), params.toString());

        //非常重要，验证回调的正确性，是不是支付宝发的，并且还要避免重复通知

        params.remove("sign");
        try {
            boolean alipayRSACheckedV2 = AlipaySignature.rsaCheckV2(params, Configs.getAlipayPublicKey(), "UTF-8", Configs.getSignType());
            if (!alipayRSACheckedV2) {
                return ServerResponse.createByErrorMessage("非法请求,验证不通过,在请求我就报警了！");
            }

        } catch (AlipayApiException e) {
            logger.error("支付宝验证回调异常...", e);
        }
        //验证各种数据
        ServerResponse serverResponse = OrderService.alipayCallback(params);
        if (serverResponse.isSuccess()) {
            return Const.AlipayCallback.RESPONSE_SUCCESS;
        }
        return Const.AlipayCallback.RESPONSE_FAILED;

    }

    @RequestMapping("query_order_pay_status.do")
    @ResponseBody
    public ServerResponse<Boolean> queryOrderPayStatus(HttpSession session, Long orderNo, HttpServletRequest request) {
        User currentUser = (User) session.getAttribute(Const.CURRENT_USER);
        if (currentUser == null) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(), ResponseCode.NEED_LOGIN.getDesc());
        }
        ServerResponse serverResponse = OrderService.queryOrderPayStatus(currentUser.getId(), orderNo);
        if (serverResponse.isSuccess()) {eBySuccess(true);
        }
        return ServerResponse.createBySuccess(false);
    }

    //原项目
    private static final List<String> CARD_TYPE_LIST;
    @Autowired
    private OrderService orderService;
    private Order order = new Order();
    private boolean shippingAddressRequired;
    private boolean confirmed;
    private List<Order> orderList;

    static {
        List<String> cardList = new ArrayList();
        cardList.add("Visa");
        cardList.add("MasterCard");
        cardList.add("American Express");
        CARD_TYPE_LIST = Collections.unmodifiableList(cardList);
    }

    public OrderController() { }

    public int getOrderId() { return this.order.getOrderId(); }

    public Order getOrder() {
        return this.order;
    }

    public void setOrder(Order order) {
        this.order = order;
    }


    public boolean isConfirmed() {
        return this.confirmed;
    }




    @GetMapping("ListOrders")
    public String listOrders(@SessionAttribute("account") Account account, Model model) {
    /*  HttpSession session = this.context.getRequest().getSession();*/
        //Account account = session.getAttribute("account");
        orderList = orderService.getOrdersByUsername(account.getUsername());
        model.addAttribute("orderList",orderList);
        return "order/ListOrders";
    }

    @GetMapping("NewOrderForm")
    public String newOrderForm(@SessionAttribute("account") Account account,/* @ModelAttribute("authenticated") authenticated,*/ @SessionAttribute("cart") Cart cart,Model model) {
    /*  HttpSession session = this.context.getRequest() Account account,@RequestParam Cart cart,Model model) {
/*        HttpSession session = this.context.getRequest().getSession();
        AccountActionBean accountBean = (AccountActionBean)session.getAttribute("/actions/Account.action");
        CartActionBean cartBean = (CartActionBean)session.getAttribute("/actions/Cart.action");*/
        //String testbreakpoint="test";
        this.clear();
        if (account != null) {
            if (cart != null) {
                order.initOrder(account, cart);
                model.addAttribute("order",order);
                List<String> creditCardTypes = new ArrayList<String>();
                creditCardTypes.add("Visa");
                creditCardTypes.add("MasterCard");
                creditCardTypes.add("American Express");
                model.addAttribute("creditCardTypes",creditCardTypes);
                return "order/NewOrderForm";
            } else {
                //this.setMessage("An order could not be created because a cart could not be found.");
                return "common/error";
            }
        } else {
            //this.setMessage("You must sign on before attempting to check out.  Please sign on and try checking out again.");
            return "Account/SignonForm";
        }
    }

    @PostMapping("NewOrder")
    public String newOrder() {
        //String testbreakpoint="test";
        //HttpSession session = this.context.getRequest().getSession();
        if (shippingAddressRequired) {
            shippingAddressRequired = false;
            return "order/ShippingForm";
        } else if (!this.isConfirmed()) {
            return "ConfirmOrderForm";
        } else if (this.getOrder() != null) {
         /*   productMapper.reduceStock(this.getOrder().getLineItems().)*/
            orderService.insertOrder(order);
            //CartActionBean cartBean = (CartActionBean)session.getAttribute("/actions/Cart.action");
            //cartcontroller.clear();
            //this.setMessage("Thank you, your order has been submitted.");
            return "order/ViewOrder";
        } else {
            //this.setMessage("An error occurred processing your order (order was null).");
            return "common/error";
        }
    }

    @GetMapping("ViewOrder")
    public String viewOrder(@SessionAttribute("account") Account account,@SessionAttribute("order") Order order,Model model) {
        //HttpSession session = this.context.getRequest().getSession();
        //AccountActionBean accountBean = (AccountActionBean)session.getAttribute("accountBean");
        if (account.getUsername().equals(order.getUsername())) {
            model.addAttribute("order",order);
            return "order/ViewOrder";
        } else {
            order = null;
            model.addAttribute("order",order);
            //this.setMessage("You may only view your own orders.");
            return "common/error";
        }
    }
    @PostMapping("ConfirmOrderForm")
    public String confirmorder(@SessionAttribute("account") Account account,@SessionAttribute("cart") Cart cart,@SessionAttribute("order") Order order,Model model){
        String testbreakpoint="test";
        orderService.insertOrder(order);
            model.addAttribute("order",order);
            return "order/ViewOrder";
    }

    public void clear() {
        this.order = new Order();
        this.shippingAddressRequired = false;
        this.confirmed = false;
        this.orderList = null;
    }
}